import {Injectable} from '@angular/core';
import {Message} from '../models/Message';
import {Thread} from '../models/Thread';
import {User} from '../models/User';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/scan';
import 'rxjs/add/operator/publishReplay';
import 'rxjs/add/operator/map';


const initialMessages: Message[] = [];

interface IMessagesOperation {
  (messages: Message[]): Message[];
}

@Injectable()
export class MessageService {

  newMessages: Subject<Message> = new Subject<Message>();
  messages: Observable<Message[]>;
  updates: Subject<any> = new Subject<any>(); // 接收用来应用到消息列表的操作
  create: Subject<any> = new Subject<any>();
  markThreadAsRead: Subject<any> = new Subject<any>();

  constructor() {
    this.messages = this.updates
      .scan((messages: Message[], operation: IMessagesOperation) => {
        return operation(messages);
      }, initialMessages)
      .publishReplay(1)
      .refCount();

    this.create.map(function (message: Message): IMessagesOperation {
      return (messages: Message[]) => {
        return messages.concat(message);
      };
    }).subscribe(this.updates); // create 连接到updates流

    this.newMessages.subscribe(this.create); // 连接到create流
    this.markThreadAsRead.map((thread: Thread) => {
      return (messages: Message[]) => {
        return messages.map((message: Message) => {
          if (message.thread.id === thread.id) {
            message.isRead = true;
          }
          return message;
        });
      };
    }).subscribe(this.updates);
  }

  addMessage(message: Message): void {
    this.newMessages.next(message);
  }

  messageForThreadUser(thread: Thread, user: User): Observable<Message> {
    return this.newMessages.filter((message: Message) => {
      return (message.thread.id === thread.id) && (message.author.id !== user.id);
    });
  }
}

export const messageServiceInjectables: Array<any> = [MessageService];
